﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace _07_WebHost.Host
{
    public class WebApplication : IApplicationBuilder
    {
        public IServiceProvider ApplicationServices { get; }

        public ILogger Logger { get; }
        private ApplicationBuilder _applicationBuilder;


        public WebApplication(IServiceProvider services)
        {
            ApplicationServices = services;
            _applicationBuilder = new ApplicationBuilder();
            Logger = services.GetRequiredService<ILogger<WebApplication>>();
        }

        public static WebApplicationBuilder Create()
        {
            return new WebApplicationBuilder();
        }



        public void Run(int port)
        {
            //得到管道
            var app = _applicationBuilder.Build();
            var scoket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            scoket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port));
            scoket.Listen();
            Logger.LogInformation("Now listening on: http://127.0.0.1:{0}", port);
            Logger.LogInformation("Application started. Press Ctrl+C to shut down.");
            scoket.Accept();
        }

        public void Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            _applicationBuilder.Use(middleware);
        }
    }
}
